package leecode

import (
	"math"
	"sort"
)

func maximumPrimeDifference(nums []int) int {
	hashMap := make(map[int][]int) //key为数组中的素数 , value为对应下标
	for index, num := range nums {
		if isPrimeL(num) {
			hashMap[num] = append(hashMap[num], index)
		}
	}
	minIndex := math.MaxInt
	maxIndex := math.MinInt
	for _, indexs := range hashMap {
		//对indexs排序
		sort.Ints(indexs)
		minIndex = min(indexs[0], minIndex)
		maxIndex = max(indexs[len(indexs)-1], maxIndex)
	}
	return maxIndex - minIndex
}

func isPrimeL(num int) bool {
	if num <= 3 {
		return num > 1
	}
	//判断是否是 6x-1 6x+1
	if num%6 != 1 && num%6 != 5 {
		return false
	}
	sqrt := int(math.Sqrt(float64(num)))
	for i := 5; i <= sqrt; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}
	return true
}
